package com.wxxymakers.grademark.config;

import com.wxxymakers.grademark.model.entity.WxIncident;
import com.wxxymakers.grademark.service.WxIncidentService;
import com.wxxymakers.grademark.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

/**
 * @AUTHOR soft
 * @DATE 2019/1/15 16:41
 * @DESCRIBE 一些定时任务
 */
@Slf4j
@Component
public class TaskConfig {

    @Autowired
    private WxIncidentService incidentService;

    @Bean
    public TaskScheduler scheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(5);
        scheduler.setThreadNamePrefix("mark-thread-");
        return scheduler;
    }

    /**
     * 每天凌晨1点
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void flushIncident() {
        WxIncident inc = incidentService.findBeganInc();
        if (inc != null) {
            if (TimeUtils.after(inc.getEndTime())) {
                if (incidentService.stop(inc.getId())) {
                    log.info("成功将事件[{}]结束！", inc.getName());
                } else {
                    log.error("未知错误导致事件结束失败！");
                }
            }
            log.info("刷新任务被执行！");
        }
    }
}
